package com.xgame.server.handler.impl;

import com.google.protobuf.InvalidProtocolBufferException;
import com.xgame.server.db.model.Accountrecord;
import com.xgame.server.dbtool.AccountrecordCsTool;
import com.xgame.server.dbtool.GameUtilTool;
import com.xgame.server.handler.Handler;
import com.xgame.server.netty.enity.MsgEntity;
import com.xgame.server.netty.proto.Cmdcode;
import com.xgame.server.netty.proto.Game;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class AccountrecordHandler implements Handler {

    private static final Logger logger = LoggerFactory.getLogger(AccountrecordHandler.class);

    @Resource
    private GameUtilTool gameUtilTool;

    @Resource
    private AccountrecordCsTool accountrecordCsTool;

    @Override
    public void doHandler(MsgEntity msgEntity, List<MsgEntity> commandList) {
        Game.AccountRecordCS account = SerialBytes2Object(msgEntity.getData());
        if (account == null) {
            logger.error("AccountRecord Parse error!！");
            return;
        }

        if (msgEntity.getCmdCode() == (int) Cmdcode.SaveCmdCode.CS_ACCOUNTRECORD_SAVE_REQ.getNumber()) {
            //上传命令
            try {
                List<Accountrecord> result = accountrecordCsTool.selectAccountRecord(account.getAccount());
                if (result.size() > 0) {
                    accountrecordCsTool.updateAccountRecord(account);
                } else {
                    accountrecordCsTool.insertAccountRecord(account);
                }
                MsgEntity resRt = gameUtilTool.getCommonResult(msgEntity.getChannel(), Cmdcode.SaveCmdCode.CS_ACCOUNTRECORD_SAVE_RES.getNumber(), 99, 0, 1, 0);
                msgEntity.getChannel().writeAndFlush(resRt);// 发送消息
            } catch (Exception e) {
                //抛出异常，错误代码：1
                logger.error("account:" + account.getAccount() + " " + e.toString());
                MsgEntity resRt = gameUtilTool.getCommonResult(msgEntity.getChannel(), Cmdcode.SaveCmdCode.CS_ACCOUNTRECORD_SAVE_RES.getNumber(), 99, 0, 0, 1);
                msgEntity.getChannel().writeAndFlush(resRt);// 发送消息
            }
        }
    }

    public static Game.AccountRecordCS SerialBytes2Object(byte[] bytes) {
        try {
            return Game.AccountRecordCS.parseFrom(bytes);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        return null;
    }
}